package com.qi.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/*
 *   自定义重写拦截器
 * */
@Component
public class LoginIntercept implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到Redis对象
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String loginUser = ops.get("user");
        if (loginUser != null) {
            //说明已经登陆，可以放行
            return true;
        }
        // 执行到这行表示未登录，未登录就重定向到到登陆页面
        response.sendRedirect("/login/goLogin");
        return false;
    }
}
